package com.wjz.commons.mongo;

import com.mongodb.client.MongoCollection;
import com.wjz.commons.entity.vo.ModelVo;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

/**
 * @author wjz
 * @date 2021/9/12 19:19
 */
@Service
@Slf4j
public class EntityService {

    @Autowired
    private MongoTemplate mongoTemplate;

    private long count(String collectionName, Bson filter) {
        MongoCollection<Document> collection = mongoTemplate.getCollection(collectionName);
        return collection.countDocuments(filter);
    }

    private void insert(String collectionName, Document doc) {
        MongoCollection<Document> collection = mongoTemplate.getCollection(collectionName);
        collection.insertOne(doc);
    }

    public void saveEntity(ModelVo modelVo, String jsonString, boolean isAllowDuplicate) {
        String tmpUrl = "entity_" + modelVo.getObjectId();
        Document doc = Document.parse(jsonString);
        if (!isAllowDuplicate) {
            Document filter = new Document();
            filter.append(modelVo.getEntryName(), doc.get(modelVo.getEntryName()));
            long qty = count(tmpUrl, filter);
            if (qty > 0) {
                log.info("record has already exsit!");
            }
        }
        insert(tmpUrl, doc);
    }
}
